package com.andova.glcamera.texture

import kotlin.math.max
import kotlin.math.min

internal class Calculator {
    fun calcCameraViewport(srcWidth: Int, srcHeight: Int, dstWidth: Int, dstHeight: Int): Viewport {
        val minSrcW = min(srcWidth, srcHeight)
        val maxSrcH = max(srcWidth, srcHeight)
        val minDstW = min(dstWidth, dstHeight)
        val maxDstH = max(dstWidth, dstHeight)
        val scaling = max(minDstW / minSrcW.toFloat(), maxDstH / maxSrcH.toFloat())
        val sw = minSrcW * scaling
        val sh = maxSrcH * scaling
        return Viewport(((minDstW - sw) / 2f).toInt(), ((maxDstH - sh) / 2).toInt(), sw.toInt(), sh.toInt())
    }

    fun calcPreviewViewport(previewWidth: Int, previewHeight: Int, surfaceWidth: Int, surfaceHeight: Int, fitFullView: Boolean = true): Viewport {
        val preW = min(previewWidth, previewHeight)
        val preH = max(previewWidth, previewHeight)
        val surW = min(surfaceWidth, surfaceHeight)
        val surH = max(surfaceWidth, surfaceHeight)

        val scaling = preW / preH.toFloat()
        val viewRatio = surW / surH.toFloat()
        val s = scaling / viewRatio

        val w: Int
        val h: Int

        if (fitFullView) {
            if (s > 1.0) {//撑满全部view(内容大于view)
                w = (surH * scaling).toInt()
                h = surH
            } else {
                w = surW
                h = (surW / scaling).toInt()
            }
        } else {
            if (s > 1.0) {//显示全部内容(内容小于view)
                w = surW
                h = (surW / scaling).toInt()
            } else {
                h = surH
                w = (surH * scaling).toInt()
            }
        }

        val x = (surW - w) / 2
        val y = (surH - h) / 2
        return Viewport(x, y, w, h)
    }
}